<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import 'element-plus/theme-chalk/el-message.css';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

// 响应式数据
const userInfo = ref({
  account: '',
  password: '',
  showPassword: false,
  loading: false,

  captcha: '',
  captchaCode: ''
});
const rules = {
  account: [
    { required: true, message: '账号不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 14, message: '密码长度要求6-14个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.toLowerCase() !== userInfo.value.captchaCode.toLowerCase()) {
          callback(new Error('验证码不正确'));
          generateCaptcha(); // 验证码错误时刷新
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}

// 路由实例
const router = useRouter();
const formRef = ref(null);
const userStore = useUserStore();
const doLogin = async () => {
    formRef.value.validate(async (valid) => {
        const { account, password } = userInfo.value;
        if (valid) {
          
          //验证通过
         await userStore.getUserInfo({account:account,password:password});
         if(userStore.loginerror==0){
          ElMessage.success('登录成功！');
          setTimeout(() => {
              router.replace('/home');
          }, 1000);
        }
        else{
          return false;
        }
        } else {
            return false;
        }
      });
}
// 验证码画布DOM引用
const captchaCanvas = ref(null);

// 切换密码显示
const togglePassword = () => {
  userInfo.value.showPassword = !userInfo.value.showPassword;
};

// 生成验证码
const generateCaptcha = () => {
  const canvas = captchaCanvas.value;
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  const width = canvas.width;
  const height = canvas.height;

  // 清空画布
  ctx.clearRect(0, 0, width, height);

  // 绘制背景
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, width, height);

  // 生成随机验证码 (4位字母数字组合)
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  userInfo.value.captchaCode = code; // 保存正确的验证码到userInfo中

  // 绘制验证码
  ctx.font = 'bold 48px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  // 每个字符使用不同的颜色和旋转角度
  for (let i = 0; i < code.length; i++) {
    const x = 20 + i * 30;
    const y = height / 2;
    const deg = Math.random() * 40 - 20; // -20到20度之间的旋转角度

    // 保存当前状态
    ctx.save();
    // 平移到字符位置
    ctx.translate(x, y);
    // 旋转
    ctx.rotate(deg * Math.PI / 180);
    // 随机颜色
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50}, ${Math.random() * 100 + 50}, ${Math.random() * 100 + 50})`;
    // 绘制字符
    ctx.fillText(code[i], 0, 0);
    // 恢复状态
    ctx.restore();
  }

  // 添加干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }

  // 添加干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200})`;
    ctx.beginPath();
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
};


// 页面挂载时执行
onMounted(() => {
  generateCaptcha();
});
</script>


<template>
  <div class="login-container">
    <div class="login-form">
      <h2>系统登录</h2>
      

      <!-- Element Plus 表单：绑定 ref、model、rules，统一标签宽度 -->
      <el-form ref="formRef" :model="userInfo" :rules="rules" status-icon label-width="80px">
        <!-- 账号表单项 -->
        <el-form-item label="账号" prop="account">
          <el-input type="text" v-model="userInfo.account" placeholder="请输入账号" />
        </el-form-item>
        
        <!-- 密码表单项：用 div 包裹输入框和显示按钮 -->
        <el-form-item label="密码" prop="password">
          <div class="password-input">
            <el-input 
              :type="userInfo.showPassword ? 'text' : 'password'" 
              v-model="userInfo.password" 
              placeholder="请输入密码"
            />
            <button 
              type="button" 
              class="toggle-password" 
              @click="togglePassword"
            >
              {{ userInfo.showPassword ? '隐藏' : '显示' }}
            </button>
          </div>
        </el-form-item>
        
        <!-- 验证码表单项：包裹输入框、画布、刷新按钮 -->
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input 
              type="text" 
              v-model="userInfo.captcha" 
              placeholder="请输入验证码"
              style="flex: 1;"
            />
            <canvas 
              ref="captchaCanvas" 
              class="captcha-canvas"
              @click="generateCaptcha"
            ></canvas>
            <button 
              type="button" 
              class="refresh-captcha" 
              @click="generateCaptcha"
            >
              刷新
            </button>
          </div>
        </el-form-item>
        
        <!-- 登录按钮 -->
        <el-form-item>
          <button 
            type="button" 
            class="login-btn" 
            @click="doLogin"
            :disabled="userInfo.loading"
          >
            <span v-if="userInfo.loading" class="loading-spinner">●●●</span>
            <span v-else>登录</span>
          </button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 600;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-form .el-form-item__label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.login-form .el-input__inner {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  transition: border-color 0.3s, box-shadow 0.3s;
  box-sizing: border-box;
}

.login-form .el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
  outline: none;
}

/* 密码输入框容器及显示/隐藏按钮样式 */
.login-form .password-input {
  position: relative;
  width: 100%; /* 让容器占满宽度 */
}

.login-form .toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: transparent;
  border: none;
  color: #667eea;
  cursor: pointer;
  font-size: 14px;
  padding: 5px;
  z-index: 10;
}

/* 验证码样式 */
.login-form .captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.login-form .captcha-canvas {
  width: 120px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
}

.login-form .refresh-captcha {
  padding: 10px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 5px;
  color: #555;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.login-form .refresh-captcha:hover {
  background-color: #e9e9e9;
}

.login-form .login-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: transform 0.3s, opacity 0.3s, background 0.3s;
}

.login-form .login-btn:hover {
  transform: translateY(-2px);
  background: linear-gradient(135deg, #5a70d8 0%, #6b489b 100%);
}

.login-form .login-btn:disabled {
  opacity: 0.8;
  cursor: not-allowed;
  transform: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.error-message {
  color: #ff4d4f;
  padding: 10px;
  margin-bottom: 20px;
  border-radius: 5px;
  background-color: rgba(255, 77, 79, 0.1);
  text-align: center;
  font-size: 14px;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>